import { Menu , Pagination} from 'antd'
import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom'
import qs from 'query-string'
import Topiclist from '../../component/Topiclist'
import store from '../../store/store'
import { LoadingOver } from '../../store/action/topic'
import http from '../../utile/axios'

//类别头部，导航栏
class IndexNav extends Component {
  state = {
    nav: [
      {
        txt: '全部',
        to: '/indexpage?tab=all',
        search: '?tab=all'
      },
      {
        txt: '精华',
        to: '/indexpage?tab=good',
        search: '?tab=good'
      },
      {
        txt: '分享',
        to: '/indexpage?tab=share',
        search: '?tab=share'
      },
      {
        txt: '问答',
        to: '/indexpage?tab=ask',
        search: '?tab=ask'
      },
      {
        txt: '招聘',
        to: '/indexpage?tab=job',
        search: '?tab=job'
      },
      {
        txt: '客户端测试',
        to: '/indexpage?tab=dev',
        search: '?tab=dev'
      }
    ],
    tab: 'all',
    page: 1,
    limit: 20,
    mdrender: true,
    defaultCurrent:1
  }
  
  //数据请求
  http = (tab,page = 1) => {
    http
      .get('/topics', {
        params: {
          tab,
          page:'all',
          limit:20,
          page,
          mdrender:true
        }
      })
      .then(data => {
        store.dispatch(LoadingOver(data.data.data))
      })
      .catch(err => {
        console.log(err)
      })
  }
  componentDidMount() {
    this.http('all')

  }
  //切换路径重新发起请求
  httpUrl = data => {
      return () => {
          const tab = qs.parse(data)
        this.http(tab.tab)
        this.setState({
          tab:tab.tab,
          defaultCurrent:1
        },() => {

        })
      }
  }
  //分页跳转 
  page = data => {
    this.http(this.state.tab,data)
    this.setState({
      defaultCurrent:data
    })
  }

  render() {
    const { data, loading } = store.getState().topic
    const { search } = this.props.location
    const {defaultCurrent} = this.state
    return (
      <div>
        {/*首页下的全部，精华等导航*/}
        <Menu
          mode={'horizontal'}
          className='indexMenu'
          defaultSelectedKeys={[search ? search : '?tab=all']}
        >
          {this.state.nav.map(item => {
            return (
              <Menu.Item key={item.search}>
                <Link to={item.to} onClick={this.httpUrl(item.search)}>{item.txt}</Link>
              </Menu.Item>
            )
          })}
        </Menu>
        {/*内容组件*/}
        <Topiclist data={data} loading={loading}></Topiclist>
        {/*分页组件*/}
        <Pagination current={defaultCurrent} total={500} 
        defaultPageSize={50}
        hideOnSinglePage
        className='componentPagination'
        onChange={this.page}
        />
        {/*
        Pagination 中的 defaultCurrent只有第一次渲染有效 坑*/}
      </div>
    )
  }
}
export default withRouter(IndexNav)
